﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Scripni.SourceControlSelector.Core;

namespace Scripni.SourceControlSelector.ConsoleApp
{
	class Program
	{
		[STAThread]
		static void Main(string[] args)
		{
			var file = GetSolutionName(args);
			if (File.Exists(file))
			{
				Configuration cfg = new Configuration();
				//get provider
				SetCurrentProvider(file, cfg);

				//start vs
				StartVisualStudio(file);

				//exit
				Application.Exit();
			}
			else
			{
				Console.WriteLine("File \"{0}\" does not exist. Cannot start Visual Studio.", file);
				Console.WriteLine("Press any key to continue.");
				Console.ReadLine();
			}
		}

		private static void SetCurrentProvider(string file, Configuration cfg)
		{
			var provider = cfg.GetProvider(Path.GetDirectoryName(file));

			//set as current
			if (provider != null)
			{
				cfg.SetCurrentProvider(provider);
			}
		}

		private static void StartVisualStudio(string file)
		{
			Process p = new Process();
			p.StartInfo = new ProcessStartInfo(
				@"C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\devenv.exe", "\"" + file + "\"");
			p.Start();
		}

		private static string GetSolutionName(string[] args)
		{
			string file;
			if (args != null && args.Any())
			{
				file = args[0];
			}
			else
			{
				FileDialog f = new OpenFileDialog();
				f.Filter = "Visual Studio Solutions (*.sln)|*.sln|All files (*.*)|*.*";
				f.ShowDialog();
				file = f.FileName;
			}
			return file;
		}
	}
}
